
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right){
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public int i;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.i = postorder.length-1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }
    public TreeNode buildTreeChild(int[] postorder, int[] inorder,int start,int end) {
        if (start > end) {
            return null;
        }
        int rootVal = postorder[i];
        i--;
        TreeNode node = new TreeNode(rootVal);
        int rootIndex = findRoot(rootVal,inorder);

        node.right = buildTreeChild(postorder,inorder,rootIndex+1,end);
        node.left = buildTreeChild(postorder,inorder,start,rootIndex-1);

        return node;
    }

    private int findRoot(int rootVal, int[] inorder) {
        for (int j = 0; j < inorder.length; j++) {
            if (inorder[j] == rootVal) {
                return j;
            }
        }
        return -1;
    }
}